<?php

namespace app\model;

use app\admin\constants\CacheConstants;
use app\exception\ParamException;
use Shopwwi\LaravelCache\Cache;
use think\Model;

/**
 *
 */
class AdminModel extends Base
{
    
    protected $name = 'admin';


    public static function getToken($admin_id){

        if(!$admin_id) throw new ParamException();

        $token = md5(uniqid($admin_id).uniqid());

        Cache::tags(CacheConstants::TAG_LOGIN_TOKEN)->set('admin_token_'.$token,$admin_id,CacheConstants::CACHE_TTL);

        $admininfo = get_admin_info($admin_id,true);

        $admininfo['token'] = $token;

        return $admininfo;

    }


    //权限验证
    public static function canAccess($app,$controller,$action){

        $request = request();

        $rules = get_admin_rules_ids();

        if(in_array('*',$rules)){
            return true;
        }

        $controller = str_replace('Controller','',end(explode("\\",$controller)));

        //判断权限是否添加到数据库
        $model = new AdminRulesModel();
        $info = $model->where([
            ['type','=',2],
            ['path','=',$app.'/'.$controller.'/'.$action],
        ])->find();

        //未添加的权限，默认放行
        if(!$info) return true;

        //验证权限
        if(in_array($info['id'],$rules)){
            return true;
        }

        return false;
    }

}
